<?php
namespace App\Http\Controllers\backend\rbac;
use App\models\rbac\AdminRole;
use App\models\rbac\Role;
use DB ;
Use App\models\Admin;
use Request;
use App\Http\Controllers\backend\Base;

class AdminController extends Base
{
    public function actionIndex(){
        if(!$this->isJson){
            return $this->view('rbac.admin.index');
        }
        return response()->json($this->page( Admin::query() ));
    }

    public function actionRoles(){
        return Role::get();
    }

    public function actionSave(){
        $id = Request::get('id',0);
        if(!$this->isPost){

            $data = '""' ;
            $roles = '[]' ;
            if($id){
                $data = Admin::select('id','name','telephone','email')->find($id)->toArray();
                $data['roles'] = AdminRole::where('admin_id',$id)->get()->pluck('role_id')->toArray();
                $data = json_encode($data) ;
            }

            return $this->view('rbac.admin.save',['data' => $data , 'roles' => $roles]);
        }

        $data = Request::all() ;
        
        $data['password'] = trim($data['password'])  ;
        if(empty($data['password'])){
            unset($data['password']) ;
        }else{
            $data['password'] = bcrypt($data['password']) ;
        }

        if($id){
            $model = Admin::find($id)->fill($data) ;
        }else{
            $model = new Admin($data);
        }

        if($model->validate($data) && $model->save()){
            // 更新关联数据
            Admin::saveRoles($data['roles'],$model->id);
            return true ;
        }
        return $model ;
    }


    public function actionDelete(){
        $id = Request::get('id',0);
        $isDelete = Admin::find($id)->delete();
        return response()->json(['code' => 0]);
    }
}